package com.ewanghuiju.app.presenter.login;

import android.widget.Toast;

import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.base.RxPresenter;
import com.ewanghuiju.app.base.contract.login.CodeLoginContract;
import com.ewanghuiju.app.model.DataManager;
import com.ewanghuiju.app.model.bean.request.LoginRequestBean;
import com.ewanghuiju.app.model.bean.response.BindUserinfoResponBean;
import com.ewanghuiju.app.model.bean.response.LoginResponBean;
import com.ewanghuiju.app.model.bean.response.PhoneCodeResponseBean;
import com.ewanghuiju.app.model.bean.response.UserInfoResponBean;
import com.ewanghuiju.app.model.http.response.MyHttpResponse;
import com.ewanghuiju.app.model.http.response.Optional;
import com.ewanghuiju.app.util.RxUtil;
import com.ewanghuiju.app.widget.CommonSubscriber;
import com.muddzdev.styleabletoast.StyleableToast;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;


/**
 * @author sj  qq:751943509
 * @class describe
 * @time 2020/2/14
 */
public class CodeLoginPresenter extends RxPresenter<CodeLoginContract.View> implements CodeLoginContract.Presenter {
    private DataManager mDataManager;
    private Disposable intervalSubscription;

    @Inject
    public CodeLoginPresenter(DataManager mDataManager) {
        this.mDataManager = mDataManager;
    }

    @Override
    public void getUserInfo() {
        addSubscribe(mDataManager.getUserInfo()
                .compose(RxUtil.<MyHttpResponse<UserInfoResponBean>>rxSchedulerHelper())
                .compose(RxUtil.handleMyResultCannull())
                .subscribeWith(new CommonSubscriber<Optional<UserInfoResponBean>>(mView) {
                    @Override
                    public void onNext(Optional<UserInfoResponBean> userInfo) {
                        if (mView != null) {
                            if (userInfo.getIncludeNull() != null) {
                                mDataManager.insertUserInfoResponBean(userInfo.getIncludeNull());
                            }
                            mView.showUserInfo(userInfo.getIncludeNull());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                })
        );
    }

    @Override
    public void phoneLogin(LoginRequestBean loginRequestBean) {
        addSubscribe(mDataManager.phoneLogin(loginRequestBean)
                        .compose(RxUtil.<MyHttpResponse<LoginResponBean>>rxSchedulerHelper())
                        .compose(RxUtil.handleMyResultCannull())
                        .subscribeWith(new CommonSubscriber<Optional<LoginResponBean>>(mView) {
                            @Override
                            public void onNext(Optional<LoginResponBean> phoneLoginResponBean) {
                                mView.showLogin(phoneLoginResponBean.getIncludeNull());
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
//                                if (e instanceof ApiException) {
//                                    mView.showLoginResponseMsg(((ApiException) e).getCode(), e.getMessage());
//                                }
                            }
                        })
        );
    }

    @Override
    public void getCode(String mobile) {
        //获取验证码
        addSubscribe(mDataManager.getCode(mobile)
                        .compose(RxUtil.<MyHttpResponse<PhoneCodeResponseBean>>rxSchedulerHelper())
                        .compose(RxUtil.handleMyResultCannull())
                        .subscribeWith(new CommonSubscriber<Optional<PhoneCodeResponseBean>>(mView) {
                            @Override
                            public void onNext(Optional<PhoneCodeResponseBean> String) {
                                StyleableToast.makeText(App.getInstance(), "获取验证码成功", Toast.LENGTH_SHORT, R.style.mytoast).show();
                                startInterval();
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
//                        if (e instanceof ApiException) {
//                            mView.showLoginResponseMsg(((ApiException) e).getCode(), e.getMessage());
//                        } else {
//                            mView.showLoginResponseMsg(Constants.NO_KNOW_EROO, e.getMessage());
//                        }
//                        StyleableToast.makeText(App.getInstance(), e.getMessage(), Toast.LENGTH_SHORT, R.style.mytoast).show();
                            }
                        })
        );
    }

    @Override
    public void startInterval() {
        final int count = 60;

        if (intervalSubscription != null && !intervalSubscription.isDisposed()) {
            return;
        }
        intervalSubscription = Flowable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)//设置循环次数
                .onBackpressureDrop()
                .compose(RxUtil.<Long>rxSchedulerHelper())
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                }).subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (mView == null)
                            return;
                        if (aLong >= count) {
                            mView.showCodeOn();
                            mView.showCodeText("重新获取(" + aLong + "s)");
                        } else if (aLong <= 0) {
                            mView.showCodeComplete();
                        } else {
                            mView.showCodeText("重新获取(" + aLong + "s)");
                        }
                    }
                });
        addSubscribe(intervalSubscription);
    }

    @Override
    public void stopInterval() {

        if (intervalSubscription != null && !intervalSubscription.isDisposed()) {
            intervalSubscription.dispose();
        }

    }

    @Override
    public void getUserNum(String unionid, String mobile, String code) {
        addSubscribe(mDataManager.getUserNum(unionid, mobile, code)
                .compose(RxUtil.<MyHttpResponse<List<BindUserinfoResponBean>>>rxSchedulerHelper())
                .compose(RxUtil.handleMyResultCannull())
                .subscribeWith(new CommonSubscriber<Optional<List<BindUserinfoResponBean>>>(mView) {
                    @Override
                    public void onNext(Optional<List<BindUserinfoResponBean>> userInfo) {
                        if (mView != null) {
                            mView.showUserNum(userInfo.getIncludeNull());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                })
        );
    }

    /**
     * 微信注册
     * @param unionid
     * @param mobile
     * @param number
     * @param headimgurl
     * @param nickname
     */
    @Override
    public void wxUserRegister(String unionid, String mobile, String number, String headimgurl, String nickname) {

        addSubscribe(mDataManager.wxUserRegister(unionid, mobile, number, headimgurl, nickname)
                .compose(RxUtil.<MyHttpResponse<LoginResponBean>>rxSchedulerHelper())
                .compose(RxUtil.handleMyResultCannull())
                .subscribeWith(new CommonSubscriber<Optional<LoginResponBean>>(mView) {
                    @Override
                    public void onNext(Optional<LoginResponBean> userInfo) {
                        if (mView != null) {
                            mView.showWxUserRegister(userInfo.getIncludeNull());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                })
        );

    }

}
